const Router = require('koa-router');
const fs = require('fs');
const mongoose = require('mongoose');
const goodsRouter = new Router();
// 获取所有商品
goodsRouter.get('/allGoods', async (ctx) => {
  // 这里读取文件的路径是相对于index文件而设置的
  await fs.readFile('./preUseFile/pureGoods.json', 'utf8', (err, data) => {
    if (err) return;
    // 将数组的buffer对象，转换为json对象
    const jsonData = JSON.parse(data);
    const Goods = mongoose.model('Goods');
    jsonData.forEach((item) => {
      // 将读到的数据，插入数据库
      const newGoods = new Goods(item);
      newGoods.save().then(() => {
        console.log('商品数据插入成功');
      }).catch((err) => {
        console.log(err);
      });
    })
  })
  ctx.body = '商品数据插入完成';
})

// 点击热卖商品或者点击小类，两个查询走一个接口，获取商品详情
goodsRouter.get('/detail', async (ctx) => {
  try {
    const goodsId = ctx.request.query.goodsId;
    const Goods = mongoose.model('Goods');
    // 操作数据库的数据是异步的
    const result = await Goods.findOne({ ID: goodsId }).exec();
    ctx.body = {
      code: 200,
      message: result,
    }
  } catch (error) {
    ctx.body = {
      code: 500,
      message: error,
    }
  }
})

// 获取大类
goodsRouter.get('/getCategory', async (ctx) => {
  try {
    const Category = mongoose.model('Category');
    const result = await Category.find().exec();
    ctx.body = {
      code: 200,
      message: result,
    }
  } catch (error) {
    ctx.body = {
      code: 500,
      message: error,
    }
  }
})

// 获取大类中的小类
goodsRouter.get('/getCategorySub', async (ctx) => {
  try {
    const CategorySub = mongoose.model('CategorySub');
    const categoryId = ctx.request.query.categoryId;
    const result = await CategorySub.find({ MALL_CATEGORY_ID: categoryId }).exec();
    ctx.body = {
      code: 200,
      message: result,
    }
  } catch (error) {
    ctx.body = {
      code: 500,
      message: error,
    }
  }
})

// 商品小类下的商品（分页）
goodsRouter.get('/getSubGoods', async (ctx) => {
  try {
    const Goods = mongoose.model('Goods');
    const query = ctx.request.query;
    const limitCount = 10;
    const skipCount = (query.currPage - 1) * limitCount;
    const result = await Goods.find({ SUB_ID: query.subId }).skip(skipCount).limit(limitCount).exec();
    ctx.body = {
      code: 200,
      message: result,
    }
  } catch (error) {
    ctx.body = {
      code: 500,
      message: error,
    }
  }
})

// 模糊搜索商品
goodsRouter.get('/searchGoods', async (ctx) => {
  const Goods = mongoose.model('Goods');
  try {
    const { goodsName, page } = ctx.request.query;
    // 模糊查询，在nodejs中必须使用RegExp来构建正则表达式对象进行模糊查询
    const regExpQuery = new RegExp(goodsName);
    const res = await Goods.find({NAME: regExpQuery}).skip(page - 1).limit(10);
    ctx.body = {
      code: 200,
      message: res,
    }
  } catch (error) {
    ctx.body = {
      code: 500,
      message: error,
    }
  }
})

module.exports = goodsRouter;